package com.edu.hre.struts.action.survey;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.cache.PassiveDynaCache;
import com.edu.hre.common.entity.HrePageInfo;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.DynamicConfig;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreSurveyEmpAnswer;
import com.edu.hre.db.pojo.HreSurveyTopic;
import com.edu.hre.db.pojo.HreSubunit;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.action.pim.EmpContactDetailUpdateAction;
import com.edu.hre.struts.form.survey.SurveyManagementListForm;
import com.edu.hre.struts.form.survey.SurveyTakeListForm;
import com.edu.hre.struts.form.survey.SurveyTakeUpdateForm;
import com.edu.hre.struts.form.survey.SurveyManagementUpdateForm;

public class SurveyTakeListAction extends DispatchAction {
	
	private static final PassiveDynaCache passiveDynaCache = BeanFinder.getBean(PassiveDynaCache.BEAN_NAME, PassiveDynaCache.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		HreUserRoleScreen userRoleScreen = (HreUserRoleScreen) request.getSession().getAttribute(RequestUtils.Attribute.HreUserRoleScreen);
		HreUser user = (HreUser) request.getSession().getAttribute(RequestUtils.Attribute.USER_INFO);
		SurveyTakeListForm beanForm = (SurveyTakeListForm) form;

		String sortBy = RequestUtils.getParameterStr(request, "sort", null);
		if (sortBy != null) { 
			beanForm.setAsc(!beanForm.isAsc());
			CommonUtils.sortCollection(beanForm.getListObjs(), beanForm.isAsc(), sortBy);
			return mapping.findForward("surveyTakeList");
		}   
		int currentPage = RequestUtils.getParameterInt(request, "page", 1);
		int pageSize = CommonUtils.parseInt(DynamicConfig.getConfig(DynamicConfig.PAGE_SIZE), 20);
		List<HreUser> listUser = baseService.getPojos(null, -1, null, null, null, 0, 0, HreUser.class);
		List<HreSubunit> listSubunit = baseService.getPojos(null, -1, null, null, null, 0, 0, HreSubunit.class);
		HreEmployee employee = baseService.getFirstPojo("empNumber", Compare.EQUAL, user.getEmpNumber(), null, null, 0, HreEmployee.class);
		List<HreSurveyTopic> listTopic = new ArrayList<HreSurveyTopic>();
		int totalItems = 0;
		if(employee != null && employee.getWorkStation() != null && employee.getWorkStation() > 0){
			List<Integer> listIdSubunit = new ArrayList<Integer>();
			HreSubunit subunit = baseService.getPojo(employee.getWorkStation(), HreSubunit.class);
			getListParentsSubunit(subunit, listIdSubunit);
			CommonUtils.println("List<Integer> listIdSubunit = " + listIdSubunit.toArray());
			listTopic = getListTopic(listIdSubunit, pageSize, pageSize * (currentPage - 1));
			totalItems = countListTopic(listIdSubunit);
		} else {
			listTopic = baseService.getPojosAnd(new String[]{"subunitId", "endDate"}, new int[]{Compare.EQUAL, Compare.GREATER}, new Object[]{1, new Date()}, new String[]{"startDate"},
					new Boolean[]{true}, pageSize, pageSize * (currentPage - 1), HreSurveyTopic.class);
			totalItems = baseService.countByColumns(new String[]{"subunitId", "endDate"}, new int[]{Compare.EQUAL, Compare.GREATER}, new Object[]{1, new Date()}, "id", HreSurveyTopic.class);
		}
		List<SurveyTakeUpdateForm> listObjs = new ArrayList<SurveyTakeUpdateForm>();
		for(int i = 0; listTopic != null && i < listTopic.size(); i++){
			HreSurveyTopic topic = listTopic.get(i);
			SurveyTakeUpdateForm obj = new SurveyTakeUpdateForm(topic.getId(), topic.getName(), topic.getSubunitId(), 
					SurveyManagementListAction.getSubunit(listSubunit, topic.getSubunitId()), topic.getStartDate(), topic.getEndDate(), 
					topic.getUserCreated(), SurveyManagementListAction.getUser(listUser, 
							topic.getUserCreated()), topic.getDateCreated(), topic.getDateModified());
			if(topic.getStartDate().compareTo(new Date()) >= 0){
				obj.setAlowUpdate(false);
			}
			HreSurveyEmpAnswer ans = baseService.getFirstPojoAnd(new String[]{"userId", "topicId"}, 
					new int[]{Compare.EQUAL, Compare.EQUAL}, new Object[]{user.getId(), topic.getId()}, HreSurveyEmpAnswer.class);
			if(ans != null){
				obj.setTaken(true);
				obj.setAlowUpdate(false);
			} else {
				obj.setTaken(false);
			}
			
			listObjs.add(obj);
		}
		beanForm.setListObjs(listObjs);
		
		List<HrePageInfo> listPages = CommonUtils.getDisplayingPages(currentPage, CommonUtils.getTotalPage(totalItems));
		beanForm.setListPages(listPages);
		beanForm.setTotalItems(totalItems);
		beanForm.setTotalPage(CommonUtils.getTotalPage(totalItems));
		String key = RequestUtils.Attribute.TAKE_SURVEY_NOTIFICATION + user.getEmpNumber();
		passiveDynaCache.setCachedItem(key, PassiveDynaCache.TIMEOUT_3_HOURS, false);
		return mapping.findForward("surveyTakeList");
	}

	private int countListTopic(List<Integer> listIdSubunit){
		String tmp = "";
		for(int i = 0; listIdSubunit != null && i < listIdSubunit.size(); i++){
			tmp += " or subunit_id = " + listIdSubunit.get(i);
		}
		String sql = "SELECT count(*) FROM hrentry_db.hre_survey_topic where end_date > sysdate() and (1 = 2 @)";
		sql = sql.replace("@", tmp);
		List<Object[]> listObjs = baseService.listArrayObject(sql, 0, 0);
		Object[] obj = listObjs.get(0);
		return ((BigInteger) obj[1]).intValue();
	}
	
	public static ArrayList<HreSurveyTopic> getListTopic(List<Integer> listIdSubunit, int limit, int offset){
		ArrayList<HreSurveyTopic> listTopic = new ArrayList<HreSurveyTopic>();
		String tmp = "";
		for(int i = 0; listIdSubunit != null && i < listIdSubunit.size(); i++){
			tmp += " or subunit_id = " + listIdSubunit.get(i);
		}
		String sql = "SELECT * FROM hrentry_db.hre_survey_topic where end_date > sysdate() and (1 = 2 @)";
		sql = sql.replace("@", tmp);
		List<Object[]> listObjs = baseService.listArrayObject(sql, limit, offset);
		for(int i = 0; listObjs != null && i < listObjs.size(); i++){
			try {
				Object[] obj = (Object[]) listObjs.get(i);
				int id = (Integer)obj[1];
				String name = (String)obj[2];
				int subunitId = (Integer)obj[3];
				Date startDate = (Date)obj[4];
				Date endDate = (Date)obj[5];
				int userCreated = (Integer)obj[6];
				Date dateCreated = (Date)obj[7];
				Date dateModified = (Date)obj[8];
				boolean showToAll = (Boolean) obj[9];
				HreSurveyTopic topic = new HreSurveyTopic(name, subunitId, startDate, endDate, userCreated, dateCreated, dateModified, showToAll);
				topic.setId(id);
				listTopic.add(topic);
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
		return listTopic;
	}
	
	public static void getListParentsSubunit(HreSubunit subunit, List<Integer> listIdSubunit) {
		if(subunit != null && subunit.getId() != null){
			listIdSubunit.add(subunit.getId());
			HreSubunit parent = baseService.getPojo(subunit.getParentId(), HreSubunit.class);
			getListParentsSubunit(parent, listIdSubunit);
		}		
	}
}
